package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;

import com.itheima.health.service.SetMealService;
import jdk.nashorn.internal.ir.annotations.Reference;

import com.itheima.health.service.ReportService;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private SetMealService setMealService;

    //统计分析-会员数量折线图展示
    @GetMapping("/getMemberReport")
    public Result getMemberReport(){
        List<String> months = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH,-12);
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH ,1);
            months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
        }
        Map<String,List> map = new HashMap<>();
        List<Integer> memberCount = memberService.findMemberCountByMonths(months);

        map.put("months",months);
        map.put("memberCount",memberCount);

        return new Result(true,MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }


    //统计分析-套餐预约占比饼形图展示
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        Map<String,Object> data = new HashMap<>();
        List<Map<String,Object>> setmealCount = setMealService.findSetmealCount();
        data.put("setmealCount",setmealCount);

        List<String> setmealNames = new ArrayList<>();
        //遍历集合取出套餐名称
        for (Map<String, Object> map : setmealCount) {
            String name = (String) map.get("name");
            setmealNames.add(name);
        }
        data.put("setmealNames",setmealNames);
        return new Result(true,MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS,data);
    }



    @Autowired
    private ReportService reportService;

    //统计运营数据统计页面展示
     @GetMapping("/getBusinessReportData")
     public Result getBusinessReportData(){
         try{
             Map<String,Object> report = reportService.getBusinessReportData();
             return new Result(true, MessageConst.GET_BUSINESS_REPORT_SUCCESS,report);
         }catch (Exception e){
             return new Result(false, MessageConst.GET_BUSINESS_REPORT_FAIL);
         }
     }
    @GetMapping("exportBusinessReport")
     public Result exportBusinessReport(HttpServletResponse response){

            log.info("[导出运营数据报表]开始");
            Map<String,Object> requst = reportService.getBusinessReportData();
            log.debug("[导出运营数据报表]rpc rsp:{}", requst);
            //取出数据准备放入Excel
            String reportDate = (String) requst.get("reportDate");
            Integer todayNewMember = (Integer) requst.get("todayNewMember");
            Integer totalMember = (Integer) requst.get("totalMember");
            Integer thisWeekNewMember = (Integer) requst.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) requst.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) requst.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) requst.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) requst.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) requst.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) requst.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) requst.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) requst.get("hotSetmeal");

        try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("report_template.xlsx");
            Workbook excel = new XSSFWorkbook(is);
            OutputStream os = response.getOutputStream()){
            Sheet sheetAt = excel.getSheetAt(0);
            Row row = sheetAt.getRow(2);
            Cell cell = row.getCell(5);
            cell.setCellValue(reportDate);

            row = sheetAt.getRow(4);
            cell= row.getCell(5);
            cell.setCellValue(todayNewMember);

            row = sheetAt.getRow(4);
            cell= row.getCell(7);
            cell.setCellValue(totalMember);

            row = sheetAt.getRow(5);
            cell= row.getCell(5);
            cell.setCellValue(thisWeekNewMember);

            row = sheetAt.getRow(5);
            cell= row.getCell(7);
            cell.setCellValue(thisMonthNewMember);

            row = sheetAt.getRow(7);
            cell= row.getCell(5);
            cell.setCellValue(todayOrderNumber);

            row = sheetAt.getRow(7);
            cell= row.getCell(7);
            cell.setCellValue(todayVisitsNumber);

            row = sheetAt.getRow(8);
            cell= row.getCell(5);
            cell.setCellValue(thisWeekOrderNumber);

            row = sheetAt.getRow(8);
            cell= row.getCell(7);
            cell.setCellValue(thisWeekVisitsNumber);

            row = sheetAt.getRow(9);
            cell= row.getCell(5);
            cell.setCellValue(thisMonthOrderNumber);

            row = sheetAt.getRow(9);
            cell= row.getCell(7);
            cell.setCellValue(thisMonthVisitsNumber);

            int rowNum = 12;
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheetAt.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名字
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }
            //使用输出流进行表格下载,基于浏览器作为客户端下载
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;fileName=" + reportDate + "_report.xlsx");//指定附件形式下载
            excel.write(os);
            os.flush();
            os.close();
            excel.close();
            return null;
        }catch (Exception e){
            return new Result(false, MessageConst.GET_BUSINESS_REPORT_FAIL);
        }
     }

}
